package com.qmyx.supply.admin.controller;

import com.qmyx.supply.admin.annotation.OperLog;
import com.qmyx.supply.admin.annotation.oplog.LogOptType;
import com.qmyx.supply.admin.annotation.oplog.annotation.OperationLog;
import com.qmyx.supply.admin.model.request.LoginRequest;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.constants.CopyWriterConstant;
import com.ytjj.qmyx.supplychain.common.constants.RedisKeyUtils;
import com.ytjj.qmyx.supplychain.common.constants.SysLogConstants;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.entity.YxAdmin;
import com.ytjj.qmyx.supplychain.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 登录管理
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class LoginController {
    @Resource
    private RedisService redisService;
    @Autowired
    private AdminService adminService;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @PostMapping("/login")
    @OperationLog(optModule = "供应链", optType = SysLogConstants.LOGIN_OPERATION, desc = "登录")
    public CommonResult login(@RequestBody LoginRequest loginRequest) {
        log.info("login");
        String redisAccountStatus = redisService.get(RedisKeyUtils.ACCOUNT_STATUS + loginRequest.getTel());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(redisAccountStatus) && "0".equals(redisAccountStatus)) {
            throw new ApiException("账号或密码输入错误次数过多，请稍后重试");
        }
        // 获取redis中的验证码
        String redisCode = redisService.get(loginRequest.getVerKey());
        String verCode = loginRequest.getVerCode();
        // 判断验证码
        if (Strings.isEmpty(loginRequest.getVerCode()) || !verCode.trim().toLowerCase().equals(redisCode)) {
            throw new ApiException("验证码不正确");
        }
        //添加用户认证信息
        String tel = loginRequest.getTel();
        String pwd = loginRequest.getPwd();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(tel, pwd, verCode);

        //对后台管理员账号进行验证
        YxAdmin adminAccount = adminService.queryByEmail(tel);
        if(adminAccount != null && adminAccount.getStatus() == 0) {
            return CommonResult.failed("您的账号存在异常，请联系管理员！");
        }
        try {
            if(subject.isAuthenticated()){
                subject.logout();
            }
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            //记录错误次数信息
//            doHandleUserNameAndPwdIsErr(tel);
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ACCOUNT_PASSWORD_FAILED));
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NO_PERMISSION));
        }
        //登录成功清除redis中错误次数信息
        Session session = subject.getSession();
        log.info("sessionInfos:{[id=" + session.getId() + "],[host=" + session.getHost() + "],[timeout=" + session.getTimeout() + "]}");

        return CommonResult.success(session.getId(), "登录成功！");
    }
}
